from pymongo import UpdateOne

from zc_core.client.mongo_client import Mongo
from zc_core.util.common import parse_time
from zc_core.util.encrypt_util import md5


def fix_order():
    mongo = Mongo(year='2020')
    update_bulk = list()
    order_list = mongo.list('order_2020', query={'orderTime': {'$gte': parse_time('2020-06-25 0:00:00')}})
    for order in order_list:
        _id = order.get('_id')
        order_user = order.get('orderUser')
        if order_user and '*' not in order_user:
            update_bulk.append(UpdateOne({'_id': _id}, {'$set': {
                '_id': _id,
                'orderUser': None,
                'orderDept': order_user,
                'deptId': md5(order_user),
                'fix': '20200703',
            }}, upsert=False))

    print(len(update_bulk))
    mongo.bulk_write('order_2020', update_bulk)
    print('任务完成~')


def fix_order_item(year_month):
    mongo = Mongo(year=year_month[:4])
    update_bulk = list()
    order_list = mongo.list('order_item_{}'.format(year_month))
    for order in order_list:
        _id = order.get('_id')
        old_order_id = order.get('orderId')
        update_bulk.append(UpdateOne({'_id': _id}, {'$set': {
            '_id': _id,
            'oid': old_order_id,
            'orderId': _id.split('_')[0],
            'fix': '20200506',
        }}, upsert=True))

    print(len(update_bulk))
    mongo.bulk_write('order_item_{}'.format(year_month), update_bulk)
    print('任务完成~')


if __name__ == '__main__':
    # fix_order()
    # fix_order_item('202001')
    # fix_order_item('202002')
    # fix_order_item('202003')
    # fix_order_item('202004')
    # fix_order_item('202005')
    # fix_order_item('202006')
    # fix_order_item('202007')
    fix_order_item('201908')
    fix_order_item('201909')
    fix_order_item('201910')
    fix_order_item('201911')
    fix_order_item('201912')
    print('over~')
